<template>
  <div class="line-chart-card">
    <div class="score-legend" v-if="showLegend">
      <div
        class="legend-item"
        v-for="(item, idx) in data.datas"
        :key="item.assessmentName"
      >
        <span
          class="dot"
          :style="{ backgroundColor: colors21[idx % colors21.length] }"
        ></span>
        <span class="legend-text">{{ item.assessmentName }}</span>
      </div>
    </div>
    <div ref="refChart" class="Chart"></div>
  </div>
</template>

<script setup>
import { ref, watch, defineProps, nextTick, onMounted, computed } from "vue";
import * as echarts from "echarts/core";
import { LineChart } from "echarts/charts";
import { GridComponent, TooltipComponent, LegendComponent } from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";

echarts.use([
  LineChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  CanvasRenderer,
]);

const colors21 = [
  "rgba(51, 196, 255, 1)",
  "rgba(4, 204, 164, 1)",
  "rgba(246, 189, 22, 1)",
  "rgba(255, 107, 59, 1)",
  "rgba(91, 143, 249, 1)",
  "rgba(255, 117, 173, 1)",
  "rgba(141, 122, 242, 1)",
  "rgba(40, 156, 203, 1)",
  "rgba(29, 172, 66, 1)",
  "rgba(195, 150, 17, 1)",
  "rgba(203, 85, 46, 1)",
  "rgba(72, 113, 198, 1)",
  "rgba(203, 93, 137, 1)",
  "rgba(112, 97, 192, 1)",
  "rgba(133, 219, 255, 1)",
  "rgba(125, 232, 153, 1)",
  "rgba(249, 215, 116, 1)",
  "rgba(255, 166, 138, 1)",
  "rgba(157, 188, 251, 1)",
  "rgba(255, 172, 206, 1)",
  "rgba(187, 175, 247, 1)",
];

const hasData = ref(false);
const refChart = ref(null);
const allData = ref([]);

const { data, showLegend } = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
  showLegend: {
    type: Boolean,
    default: true,
  },
});

// console.log("props data: ", data);
const refData = computed(() => data);

const toSeriers = (datas) => {
  if (!datas) return [];
  return datas.map((item, idx) => {
    // 处理数据，为null值设置特殊的symbol配置
    const processedData = item.score.map((value) => {
      if (value === null || value === undefined) {
        return {
          value: value,
          // symbol: "none", // null值不显示数据点
          symbolSize: 0,
        };
      }
      return value;
    });

    return {
      name: item.assessmentName,
      type: "line",
      smooth: true,
      smoothMonotone: "x",
      data: processedData,
      color: colors21[idx % colors21.length],
      connectNulls: true, // 连接null值，避免连线断开
      symbol: "circle", // 数据点样式
      symbolSize: 4, // 数据点大小
      lineStyle: {
        width: 2,
      },
    };
  });
};

onMounted(() => {
  init();
});

// x轴数据 ["12"]
const xAxisLabels = computed(() => data.reportTimes || []);

let myChart = null;
const init = () => {
  nextTick(() => {
    if (!refChart.value) {
      this.init();
      return;
    }
    myChart = echarts.init(refChart.value, "light");
    update();
  });
};

const update = () => {
  if (!myChart) return;
  const reportTimes = data?.reportTimes || [];
  hasData.value = allData.value.length > 0 && reportTimes.length > 0;

  const getShowParam = (params) => {
    console.log("getShowParam: ", params);
    const typeStr = params.seriesName;
    // 如果值为null或undefined，显示暂无数据
    if (params.value === null || params.value === undefined) {
      return `${params.name}<br/>${typeStr}：暂无数据`;
    }
    return `${params.name}<br/>${typeStr}：${Number(params.value).toFixed(2)}分`;
  };
  const option = {
    xAxis: {
      type: "category",
      data: xAxisLabels.value || [],
      axisLabel: {
        align: "center",
        color: "#8C8C8C",
      },
      axisTick: {
        alignWithLabel: true,
      },
      axisLine: {
        lineStyle: {
          color: "#8C8C8C",
        },
      },
    },
    yAxis: {
      splitLine: {
        show: true,
        lineStyle: {
          type: "dashed",
          color: "#E5E5E5",
        },
      },
      axisLabel: {
        color: "#8C8C8C",
      },
      axisLine: {
        lineStyle: {
          color: "#8C8C8C",
        },
      },
    },
    series: toSeriers(data.datas),
    markLine: {
      symbol: "none",
      data: [
        {
          xAxis: reportTimes[Math.floor(reportTimes.length / 2)],
        },
      ],
      lineStyle: {
        color: "#ff4d4f",
        type: "dashed",
        width: 2,
      },
      label: {
        show: false,
      },
    },
    tooltip: {
      trigger: "item",
      formatter: getShowParam,
    },
    grid: {
      left: "40", // 距离左侧的距离
      right: "5%", // 距离右侧的距离
      top: "24px", // 距离顶部的距离
      bottom: "30", // 距离底部的距离
    },
  };
  myChart.setOption(option);
};

// 监听数据变化
watch(
  refData,
  () => {
    update();
  },
  { deep: true }
);
</script>

<style scoped lang="less">
.line-chart-card {
  background: #fff;
  border-radius: 16px;
  padding: 20px;
  box-sizing: border-box;
  width: 100%;
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.Chart {
  height: 260px;
  width: 100%;
}

.score-legend {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 24px; // 行间距8px，列间距24px
  margin-bottom: 12px;

  .legend-item {
    display: flex;
    align-items: center;
  }
}
.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 8px;
}

.legend-text {
  height: 20px;
  font-size: 12px;
  color: #8c8c8c;
  line-height: 20px;
}

.red {
  background-color: #ff4d4f;
}

.orange {
  background-color: #fa8c16;
}

.blue {
  background-color: #436bff;
}

.green {
  background-color: #52c41a;
}
</style>
